create function wp_GetObjectState(
	@object int,
	@branchID int,
	@stateto int)
returns int
as
begin
		declare @objectstate int
		declare @infostate int
		declare @statefrom int
		declare @newbranchid int

		set @objectstate = null
		set @infostate = null
		set @statefrom = null
		select @statefrom = SourceState from Branch where ID = @branchID

		declare d cursor for
			select State from Data
				where ObjectID = @object
					and State > coalesce(@statefrom, State-1)
					and State <= coalesce(@stateto, State)
				order by State desc

		open d

		fetch next from d into @objectstate
		while @@fetch_status = 0
		begin
			select @infostate = max(State) from Info where State <= @objectstate
			if isnull(@branchid, 0) <> 0
			begin
				if (select BranchID from Info where State = @infostate) = @branchid
				begin
					close d
					deallocate d
					return @objectstate
				end
			end
			else
			begin
				if (select BranchID from Info where State = @infostate) is null
				begin
					close d
					deallocate d
					return @objectstate
				end
			end
			fetch next from d into @objectstate
		end

		close d
		deallocate d

		if isnull(@branchID, 0) = 0
			return -1

		select @infostate = max(State) from Info where State <= @statefrom
		select @newbranchid = BranchID from Info where State = @infostate
		select @objectstate = dbo.wp_GetObjectState(@object, @newbranchid, @statefrom)
		return @objectstate
end